{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## LRU Least Recently Used"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "LRU是Least Recently Used的缩写，即最近最少使用，是一种常用的页面置换算法，选择最近最久未使用的页面予以淘汰。\n",
    "该算法赋予每个页面一个访问字段，用来记录一个页面自上次被访问以来所经历的时间t，当须淘汰一个页面时，选择现有页面中其 t 值最大的，即最近最少使用的页面予以淘汰。在有限的空间中存储对象时，当空间满时，会按一定的原则删除原有的对象，常用的原则（算法）有LRU，FIFO等\n",
    "\n",
    "<img src=\"./lru.jpg\" style=\"margin-left:0px;\"/>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class LRUCache(object):\n",
    "    def __init__(self, capacity):\n",
    "        self.capacity = capacity\n",
    "        # 存储数据\n",
    "        self.values = {}\n",
    "        # 存储使用的顺序\n",
    "        self.access = []\n",
    "\n",
    "    def get(self, key):\n",
    "        \"\"\"查询的时候，会影响元素的位置，把这个元素放到最后\"\"\"\n",
    "        if key in self.values:\n",
    "            self.access.remove(key)\n",
    "            self.access.append(key)\n",
    "            return self.values[key]\n",
    "        else:\n",
    "            return -1\n",
    "\n",
    "    def set(self, key, value):\n",
    "        if key in self.values:\n",
    "            self.access.remove(key)\n",
    "        elif len(self.values) >= self.capacity:\n",
    "            # 清理最不常用的元素\n",
    "            del self.values[self.access.pop(0)]\n",
    "        self.access.append(key)\n",
    "        self.values[key] = value\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{5: 50, 6: 60, 7: 70, 8: 80, 9: 90} [5, 6, 7, 8, 9]\n"
     ]
    }
   ],
   "source": [
    "lru = LRUCache(5)\n",
    "for i in range(5,10):\n",
    "    lru.set(i, 10*i)\n",
    "print(lru.values, lru.access)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{5: 50, 6: 60, 7: 70, 8: 80, 9: 90} [6, 7, 8, 9, 5]\n",
      "{5: 50, 7: 70, 8: 80, 9: 90, 10: 100} [7, 8, 9, 5, 10]\n"
     ]
    }
   ],
   "source": [
    "lru.get(5)\n",
    "print(lru.values, lru.access)\n",
    "lru.set(10,100)\n",
    "print(lru.values, lru.access)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
